package com.ioudi.digu.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ioudi.digu.dao.support.IQuerySupport;
import com.ioudi.digu.vo.MessageSelector;


public class MessageSelectorDAO extends HibernateDaoSupport
{
	private IQuerySupport querySupport;
	
	public MessageSelector saveMessageSelector(MessageSelector selector)
    {
        Session s = this.getSession();
        try
        {
        	s.beginTransaction();
        	s.save(selector);
        	s.getTransaction().commit();
        }
        catch(Exception e)
        {
        	selector = null;
        	s.getTransaction().rollback();
        }
        finally
        {
        	s.close();
        }
    	return selector;
    }
	
	public MessageSelector getMessageSelector(String user)
    {
        Session s = this.getSession();
        MessageSelector result = null;
        try
        {
        	s.beginTransaction();
        	Object o = s.createQuery("from MessageSelector selecor where selecor.user=:user").
    	    setString("user", user).uniqueResult();
        	if(o != null)
        	{
        		result = (MessageSelector)o;
        	}
        	s.getTransaction().commit();
        }
        catch(Exception e)
        {
        	s.getTransaction().rollback();
        }
        finally
        {
        	s.close();
        }
    	return result;
    }
	
	public boolean updateMessageSelector(String user, Map change)
	{
		Session s = this.getSession();
        boolean result = false;
        if(change == null || user == null)
        {
        	return false;
        }
        List<String> keys = new ArrayList<String>();
        String sql = "update MessageSelector selecor set ";
        sql += querySupport.createStatement("selecor", change, keys);
        sql += " where selecor.user = ?";
        keys.add("user");
        change.put("user", user);
        try
        {
        	s.beginTransaction();
        	Query query = s.createQuery(sql);
        	querySupport.createQuery(query, keys, change).executeUpdate();
        	s.getTransaction().commit();
        	result = true;
        }
        catch(Exception e)
        {
        	s.getTransaction().rollback();
        }
        finally
        {
        	s.close();
        }
	    return result;
	}
	
	public IQuerySupport getQuerySupport()
	{
		return querySupport;
	}

	public void setQuerySupport(IQuerySupport querySupport)
	{
		this.querySupport = querySupport;
	}
}
